<template>
    <el-row :gutter="13">
        <el-col :span="8">
            <el-card>
                <!-- 用户未的未读消息提示框 -->
                <el-dropdown ref="dropdown1" trigger="contextmenu">
                    <span class="el-dropdown-link" style="border: 1px solid black; width: 510px;"></span>
                    <template #dropdown>
                        <el-table :data="data.informationTips" @cell-click="handleCellClick"
                            style="width: 500px;height: 768px;">
                            <el-table-column prop="recipient" label="联系人" />
                            <el-table-column prop="unreadQuantity" label="未读消息" align="center" />
                        </el-table>
                    </template>
                </el-dropdown>

                <div style="background-color: #F3F3F3; width: 100%; margin-left: 10px;">
                    <el-button style="margin-bottom: 5px;"><el-icon>
                            <Stamp />
                        </el-icon>接 收 人</el-button>
                    <el-button style="margin-bottom: 5px;" @click="showClick">未读信息</el-button>
                    <el-table :data="filterTableData" style="width: 100%" height="705">
                        <el-table-column class="contactAll" label="联 系 人" prop="name" />
                        <el-table-column class="contactAll" align="right">
                            <template #header>
                                <el-input v-model="data.search" size="small" placeholder="搜 索 联 系 人" />
                            </template>
                             <!--    联系人    -->
                            <template #default="scope" class="manp">
                                <el-button size="small" @click="sendMsg(scope.$index, scope.row)">
                                    <el-icon style="margin-right: 2px;">
                                        <List/>
                                    </el-icon>发送
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-card>
        </el-col>
        <el-col :span="16">
            <el-card :style="{ display: data.showChatFrame ? 'none' : 'block' }">
                <div><img style="border-radius: 10px;width: 100%;height: 756px;" src="../../assets/image/chat-frame/chat-frame.png" alt=""></div>
            </el-card>
            <el-card :style="{ display: data.showChatFrame ? 'block' : 'none' }">
                <div style="height: 22px;margin-bottom: 15px;">
                    <h3>{{ data.recipient }}</h3>
                </div>
                <!-- 聊天的内容 对话内容 -->
                <div ref="messageContainer" class="chat-container" @open="scrollToBottom">
                    <div v-for="message in data.messages" :key="message.id"
                        :class="['message-' + (message.from === 'me' ? 'right' : 'left')]">
                        <span>{{ message.text }}</span>
                        <div class="beanr"></div>
                    </div>
                </div>
                <el-row :gutter="10">
                    <el-col :span="22">
                        <el-input v-model="data.form.content" placeholder="请输入聊天内容" type="textarea" resize="none"
                            style="border: 1px solid #77B3EB;border-radius: 4px;"></el-input>
                    </el-col>
                    <el-col :span="2">
                        <el-button type="primary" style="height: 54px;width: 75px;margin-left: 10px;"
                            @click="handleMsg">发送</el-button>
                    </el-col>
                </el-row>
            </el-card>
        </el-col>
    </el-row>
</template>

<script setup>
import { chattingRecordsBySenderAndRecipient, selectAllLinkman, senderExchange, senderUnreadQuantity, updateUnread } from '@/api/relation';
import { useUserStore } from '@/stores/user';
import { ElMessage } from 'element-plus';
import { computed, reactive, ref } from 'vue';


const data = reactive({
    tableData: [], //存放联系人
    messages: [],
    showDialogMsg: true, //发送信息的控制器

    sender: '', //发送人
    recipient: '', //接收人
    form: {},

    informationTips: [], //信息提示

    showChatFrame: false, //聊天空白显示控制器

})


const messageContainer = ref()  //控制对话框的聊天内容 滚动
const dropdown1 = ref()
function showClick() {
    if (!dropdown1.value) return
    dropdown1.value.handleOpen()
}

const handleCellClick = async (row, column, cell, event) => {
    data.showChatFrame = true
    const userObj = useUserStore()
    let loggedder = userObj.user.name;
    data.sender = loggedder
    data.recipient = row.recipient
    //通过未读信息点击后 ------> 与未读人的聊天聊天框
    await chattingRecordsBySenderAndRecipient(loggedder, row.recipient).then(res => {
        data.messages = res.data.data.sort(((a, b) => new Date(b.sendTime) - new Date(a.sendTime)))
        data.messages = data.messages.map(item => ({
            id: item.id,
            from: item.sender === loggedder ? 'me' : 'them',
            text: item.content
        }))
        data.messages = data.messages.reverse()
    })
    scrollToBottom()
    await updateUnread(loggedder, row.recipient).then(res => {
        if(!res.data.code == '200'){
            ElMessage.error('系统有误')
        }
    })   
}

//让聊天返回到最下面
const scrollToBottom = () => {
    if (messageContainer.value) {
        messageContainer.value.scrollTop = messageContainer.value.scrollHeight
    }
}


const filterTableData = computed(() =>
    data.tableData.filter((item) =>
        !data.search || item.name.toLowerCase().includes(data.search.toLowerCase())
    )
)

const sendMsg = async (index, row) => {
    data.showChatFrame = true
    const userObj = useUserStore()
    let loggedder = userObj.user.name;
    data.sender = loggedder
    data.recipient = row.name
    //在这个查看聊天人的对话中 将他的未读信息转化为已读信息


    await chattingRecordsBySenderAndRecipient(loggedder, row.name).then(res => {
        data.messages = res.data.data.sort(((a, b) => new Date(b.sendTime) - new Date(a.sendTime)))
        data.messages = data.messages.map(item => ({
            id: item.id,
            from: item.sender === loggedder ? 'me' : 'them',
            text: item.content
        }))
        data.messages = data.messages.reverse()
    })
    scrollToBottom()
    setInterval(fetchChatRecords,5000)
}

const handleMsg = async () => {
    const userObj = useUserStore()
    data.form.sender = userObj.user.name
    data.form.recipient = data.recipient
    await senderExchange(data.form).then(res => {
        console.log(res);
        if (res.data.code == '200') {
            data.form.content = ''
            fetchChatRecords()
        } else {
            ElMessage.error('失败')
        }
    })
}

//实现聊天的发送者发完信息以后可以立马在屏幕上刷新  (简易的自刷新)
const fetchChatRecords = async () => {
    const userObj = useUserStore()
    await chattingRecordsBySenderAndRecipient(userObj.user.name, data.recipient).then(res => {
        const newMessages = res.data.data.sort(((a, b) => new Date(b.sendTime) - new Date(a.sendTime)));
        const updatedMessages = newMessages.map(item => ({
            id: item.id,
            from: item.sender === userObj.user.name ? 'me' : 'them',
            text: item.content
        }))
        data.messages = updatedMessages.reverse();
        scrollToBottom()
    })
}

const load = async () => {
    //获取联系人
    await selectAllLinkman().then((res) => {
        data.tableData = res.data.data
    })

    const userObj = useUserStore()
    await senderUnreadQuantity(userObj.user.name).then(res => {
        data.informationTips = res.data.data
        console.log(data.informationTips);
    })
}

load()


//右侧图片，角定位改变

</script>

<style lang="scss" scoped>
.example-showcase .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
}

.dialog-custom-class {
    box-sizing: border-box;
    position: fixed;
}

.message-left {
    margin:10px 45px;//添加属性为了放图片
}

.message-left span {
    display: inline-block;
    background-color: rgba(200,200,200,0.5);
    padding: 10px;
    border-radius: 5px;
    max-width: 60%;
    margin-left: 10px;
}
//伪元素图片
.message-left:before{
  content: "";
  width: 35px;
  height: 35px;
  border-radisu:3px;
  display: block;
  background:url("../../assets/background.jpg") no-repeat center center;
  background-size: 200%;
  position: relative;
  left: -35px;
  top: 37px;
  z-index: 50;
}

//伪元素做小角3
.message-left:after{
  content: "";
  display: block;
  width: 0;
  height: 0;
  border: 4px solid transparent;
  border-right:4px solid rgba(200,200,200,0.5);
  position: relative;
  top: -40px;
  left: 2px;
}
.message-right {
    margin:10px 10px;//添加属性为了放图片
    display: flex;
    justify-content: right;
}

.message-right span {
    display: inline-block;
    background-color: #cfe7ff;
    padding: 10px;
    border-radius: 5px;
    max-width: 60%;
    margin-right: 10px;
}
//右侧伪元素图片
.message-right:after{
  content: "";
  width: 35px;
  height: 35px;
  border-radisu:3px;
  display: block;
  background:url("../../assets/background.jpg") no-repeat center center;
  background-size: 200%;
  position: relative;
  right: 0;
  top: 0;
  z-index: 50;
}

//伪元素做小角右侧
.beanr{
  width: 0;
  height: 0;
}
.beanr:after{
  content: "";
  display: block;
  width: 0;
  height: 0;
  border: 4px solid transparent;
  border-left:4px solid #cfe7ff;
  position: relative;
  top: 10px;
  right: 10px;
}
.chat-container {
    height: 670px;
    overflow-y: auto;
    overflow-anchor: none;
    margin-bottom: 15px;
    border: 1px solid #ccc;
    border-radius: 10px;
}

.chat-container::-webkit-scrollbar {
    display: none;
}



.manp{
  padding: 0 20px;
}
</style>